package com.hh.bss.mail;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


import javax.mail.util.ByteArrayDataSource;

import org.hibernate.util.StringHelper;

import com.hh.bss.util.MailAuthenticator;


public class SendMailUtil {


	private static byte[] getFileBytes(File file) {
		byte[] myData = null;
		InputStream input = null;
		try {
			input = new BufferedInputStream(new FileInputStream(file));
			ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
			int ch = 0;
			while ((ch = input.read()) != -1) {
				byteArray.write(ch);
			}

			myData = byteArray.toByteArray();

		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			   try{if (input!=null)input.close();}catch(Exception ex1){ex1.printStackTrace();}	
			}
		return myData;
	}



	public static boolean sendNoticeMail(SendMailInfo mailInfo){
		//设置邮件smtp信息
		Properties pos = new Properties();
		pos.put("mail.smtp.host", mailInfo.getMailServerAddress());
		pos.setProperty("mail.transport.protocol", "smtp");
		pos.put("mail.smtp.port", mailInfo.getPort());
		
		pos.put("mail.smtp.auth", mailInfo.isAuth()?"true":"false");
		javax.mail.Session mailSession=null;
		if (mailInfo.isAuth()){
		 mailSession = javax.mail.Session.getDefaultInstance(pos,
				new MailAuthenticator(mailInfo.getUser(), mailInfo.getPassword()));
		}else{
			mailSession=javax.mail.Session.getDefaultInstance(pos);
		}
		
		//设置邮件信息
		MimeMessage msg = new MimeMessage(mailSession);
		try {
			//判断是否需要回执
			msg.setHeader("X-Mailer", "Microsoft Office Outlook 12.0");
			if(mailInfo.getReplysign()){
				msg.addHeader("Disposition-Notification-To",mailInfo.getSenderAddress());
			}
			msg.setFrom(new InternetAddress(mailInfo.getSenderAddress()));
			msg.setSubject(mailInfo.getTitle());
			msg.setSentDate(new Date());
			Address[] adds = InternetAddress.parse(mailInfo.getToAddress());
			
			//设置收件人
			msg.addRecipients(javax.mail.Message.RecipientType.TO, adds);
			
			//设置cc人
			if (!StringHelper.isEmpty(mailInfo.getCcAddress())){
				  Address[] ccadds = InternetAddress.parse(mailInfo.getCcAddress());
				  msg.addRecipients(javax.mail.Message.RecipientType.CC, ccadds);
			}
			//设置暗抄人
			if (!StringHelper.isEmpty(mailInfo.getBCcAddress())){
				  Address[] bccadds = InternetAddress.parse(mailInfo.getBCcAddress());
				  msg.addRecipients(javax.mail.Message.RecipientType.BCC, bccadds);
			}
			
			
			// 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
			MimeMultipart mm = new MimeMultipart("related");
			
			// 新建一个存放信件内容的BodyPart对象（邮件主体内容）
			BodyPart mdp = new MimeBodyPart();
			// 给BodyPart对象设置内容和格式/编码方式
			//设置邮件内容
			mdp.setContent(mailInfo.getContent(), "text/html;charset=utf-8");
			
			// 把内容加到邮件多媒体包体，这句很重要，千万不要忘了
			mm.addBodyPart(mdp);
			
			//处理图片
			
			//处理附件
			Map m=mailInfo.getAttachmentFiles();
			String key;
			//名称，路径
			int i=0;
			for(Iterator it=m.keySet().iterator();it.hasNext();){
				key=(String)it.next();
				i++;
				String path=(String)m.get(key);
				File f=new File(path);
				//附件存在才处理
				if (f.exists()){
					BodyPart mdp_atta = new MimeBodyPart();
					DataHandler dh = new DataHandler(new ByteArrayDataSource(
							getFileBytes(f), "application/octet-stream"));
					mdp_atta.setDataHandler(dh);
					// 加上这句将作为附件发送,否则将作为信件的文本内容
					try {						
						//mdp_atta.setFileName(MimeUtility.encodeWord(f.getName()));
						System.out.println("----------------------"+key);
						mdp_atta.setFileName(MimeUtility.encodeWord(key));
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
										
					mdp_atta.setHeader("content-id"+i, "<ATTA1>");
					mm.addBodyPart(mdp_atta);
				}
			}
			//处理附件结束
			
			msg.setContent(mm);
			msg.saveChanges();
			javax.mail.Transport transport = mailSession.getTransport("smtp");
			transport.connect();
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
			return true;
			
		} catch (AddressException e) {
			e.printStackTrace();
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
		
		
		
		
    }
	public static void main(String[] arg){
		//SendMailUtil.sendNoticeMail("my email","2012","","myabc112@sina.com",null);
		//logic.setToAddress("30450081@qq.com,wangwenhao@vv8.com");
		//logic.setContent("<html><body><img src=\"cid:IMG1\">测试邮件<body><html>");
//		pos.put("mail.smtp.host", "smtp.sina.com");
//		pos.setProperty("mail.transport.protocol", "smtp");
//		pos.put("mail.smtp.port", "25");
//		pos.put("mail.smtp.auth", "true");
//		javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(pos,
//				new MailAuthenticator("myabc112@sina.com", "myabc112"));
		SendMailInfo sendMailInfo=new SendMailInfo();
		sendMailInfo.setMailServerAddress("smtp.sina.com");
		//sendMailInfo.setMailServerAddress("smtp.talent-bank.cn");
		//
		sendMailInfo.setAuth(true);
		sendMailInfo.setUser("myabc112@sina.com");		
		sendMailInfo.setPassword("myabc112");
		//sendMailInfo.setUser("test@talent-bank.cn");
		//sendMailInfo.setPassword("tbgz2012");
		sendMailInfo.setTitle("测试Email");
		sendMailInfo.setContent("<html><body><img src=\"cid:IMG1\">测试邮件<body><html>");
		sendMailInfo.setSenderAddress("myabc112@sina.com");
		//sendMailInfo.setSenderAddress("test@talent-bank.cn");
		sendMailInfo.setToAddress("30450081@qq.com");
		//sendMailInfo.getAttachmentFiles().put("pic", "f:/a.doc");
		sendMailInfo.getAttachmentFiles().put("pic2", "f:/61_vv8.gif");
		
		SendMailUtil.sendNoticeMail(sendMailInfo);
		
	}
	
}
